import Imap from 'imap';
import { simpleParser } from 'mailparser';

export const onMessage = (cb = (seqNo, message) => { }) => {
    // const imap = new Imap({
    //     user: process.env.EMAIL_ACCOUNT,
    //     password: process.env.EMAIL_PWD,
    //     host: process.env.EMAIL_HOST,
    //     port: process.env.EMAIL_PORT,
    //     tls: true
    // });

    const imap = new Imap({
        user: 'xqq.funds@aliyun.com',
        password: 'Chen362133',
        host: 'imap.aliyun.com',
        port: 993,
        tls: true
    });

    function openInbox(cb) {
        console.log('openInbox start...');
        imap.openBox('INBOX', false, cb);
    }

    imap.once('ready', function () {
        openInbox(function (err, box) {
            if (err) throw err;
            imap.search(['UNSEEN'], function (err, results) {
                if (err) throw err;
                if (results.length === 0) {
                    console.log('No new emails.');
                    imap.end();
                    return;
                }
                const f = imap.fetch(results, { bodies: '' });

                f.on('message', function (msg, seqno) {
                    msg.on('body', function (stream, info) {
                        simpleParser(stream, (err, mail) => {
                            if (err) throw err;
                            cb(seqno, {
                                subject: mail.subject,
                                from: mail.from.value[0].address,
                                html: mail.html
                            });
                        });
                    });
                    msg.once('attributes', function (attrs) {
                        const { uid } = attrs;
                        imap.addFlags(uid, ['\\Seen'], function (err) {
                            if (err) {
                                console.log('Error marking email as read:', err);
                            } else {
                                console.log('Marked email as read.');
                            }
                        });
                    });
                });

                f.on('end', function () {
                    console.log('Done fetching all messages!');
                    imap.end();
                });
            });
        });
    });

    imap.once('error', function (err) {
        console.log('IMAP error: ' + err);
    });

    imap.once('end', function () {
        console.log('Connection ended');
    });

    imap.connect();
}


